<template>
  <div class="club-list-container">
    <el-card class="page-header">
      <div class="header-content">
        <h1>社团活动</h1>
        <div class="actions">
          <el-input
            v-model="keyword"
            placeholder="搜索活动"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          
          <el-button v-if="isAdmin" type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>发布活动
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 活动列表 -->
    <div v-loading="loading" class="activities-container">
      <div v-if="activities.length === 0" class="empty-state">
        <el-empty description="暂无活动" />
      </div>
      
      <el-row :gutter="20">
        <el-col v-for="activity in activities" :key="activity.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="activity-card" shadow="hover" @click="viewActivityDetail(activity.id)">
            <div class="activity-image">
              <img :src="activity.imageUrl || defaultImage" alt="活动图片" />
              <div class="activity-status" v-if="!activity.isActive">
                <span>已取消</span>
              </div>
            </div>
            <div class="activity-info">
              <h3 class="activity-title">{{ activity.title }}</h3>
              <p class="activity-desc">{{ truncateText(activity.description, 80) }}</p>
              <div class="activity-meta">
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDateTime(activity.startTime) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ activity.location }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>{{ activity.currentParticipants }}/{{ activity.maxParticipants }}</span>
                </div>
              </div>
              <div class="activity-footer">
                <el-tag 
                  :type="activity.isRegistered ? 'success' : ''" 
                  effect="plain" 
                  size="small"
                >
                  {{ activity.isRegistered ? '已报名' : '未报名' }}
                </el-tag>
                <span class="creator">发布者: {{ activity.createdByName }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="query.page"
          v-model:page-size="query.size"
          :page-sizes="[8, 16, 24, 32]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建活动对话框 -->
    <el-dialog
      v-model="createDialog.visible"
      title="发布活动"
      width="650px"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityRules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="activityForm.title" placeholder="请输入活动标题" />
        </el-form-item>
        
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="5"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number
            v-model="activityForm.maxParticipants"
            :min="1"
            :max="1000"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="活动图片" prop="imageUrl">
          <el-input v-model="activityForm.imageUrl" placeholder="请输入图片URL地址" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialog.visible = false">取消</el-button>
          <el-button type="primary" :loading="createDialog.loading" @click="submitActivity">
            发布活动
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Search, Plus, Calendar, Location, User } from '@element-plus/icons-vue'
import { getActivities, searchActivities, createActivity } from '@/api/club'

// 默认活动图片
const defaultImage = 'https://via.placeholder.com/400x200?text=Activity'

const router = useRouter()
const store = useStore()

// 用户权限
const isAdmin = computed(() => {
  const userInfo = store.state.user.userInfo
  return userInfo && userInfo.role === 'ADMIN'
})

// 查询参数
const keyword = ref('')
const query = reactive({
  page: 1,
  size: 8,
  sortBy: 'startTime',
  direction: 'asc'
})

// 数据状态
const loading = ref(false)
const activities = ref([])
const total = ref(0)

// 创建活动对话框
const createDialog = reactive({
  visible: false,
  loading: false
})

// 活动表单
const activityFormRef = ref(null)
const activityForm = reactive({
  title: '',
  description: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: 50,
  imageUrl: ''
})

// 表单验证规则
const activityRules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2-100个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' },
    { min: 10, max: 2000, message: '描述长度在10-2000个字符之间', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value && new Date(value) < new Date()) {
          callback(new Error('开始时间不能早于当前时间'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value && activityForm.startTime && new Date(value) <= new Date(activityForm.startTime)) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' },
    { min: 2, max: 200, message: '地点长度在2-200个字符之间', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大人数', trigger: 'change' },
    { type: 'number', min: 1, message: '人数必须大于0', trigger: 'change' }
  ]
}

// 获取活动列表
const fetchActivities = async () => {
  loading.value = true
  try {
    // 准备参数
    const params = {
      page: query.page - 1, // 后端从0开始计数
      size: query.size,
      sortBy: query.sortBy,
      direction: query.direction
    }
    
    // 发送请求
    const response = await getActivities(params)
    
    if (response && response.data) {
      activities.value = response.data.activities || []
      total.value = response.data.totalItems || 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索活动
const handleSearch = async () => {
  if (!keyword.value.trim()) {
    return fetchActivities()
  }
  
  loading.value = true
  try {
    const params = {
      page: query.page - 1,
      size: query.size
    }
    
    const response = await searchActivities(keyword.value.trim(), params)
    
    if (response && response.data) {
      activities.value = response.data.activities || []
      total.value = response.data.totalItems || 0
    }
  } catch (error) {
    console.error('搜索活动失败:', error)
    ElMessage.error('搜索活动失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 查看活动详情
const viewActivityDetail = (activityId) => {
  router.push(`/club/detail/${activityId}`)
}

// 显示创建活动对话框
const showCreateDialog = () => {
  createDialog.visible = true
  
  // 重置表单
  Object.assign(activityForm, {
    title: '',
    description: '',
    startTime: '',
    endTime: '',
    location: '',
    maxParticipants: 50,
    imageUrl: ''
  })
  
  // 重置表单验证
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
}

// 提交活动表单
const submitActivity = () => {
  activityFormRef.value.validate(async (valid) => {
    if (valid) {
      createDialog.loading = true
      try {
        await createActivity(activityForm)
        ElMessage.success('活动发布成功')
        createDialog.visible = false
        
        // 刷新活动列表
        fetchActivities()
      } catch (error) {
        console.error('发布活动失败:', error)
        ElMessage.error('发布活动失败: ' + (error.message || '未知错误'))
      } finally {
        createDialog.loading = false
      }
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  query.size = size
  fetchActivities()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  query.page = page
  fetchActivities()
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 初始化
onMounted(() => {
  fetchActivities()
})
</script>

<style lang="scss" scoped>
.club-list-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
      }
      
      .actions {
        display: flex;
        gap: 15px;
        
        .search-input {
          width: 300px;
        }
      }
    }
  }
  
  .activities-container {
    .activity-card {
      height: 100%;
      margin-bottom: 20px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
      }
      
      .activity-image {
        position: relative;
        height: 180px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .activity-status {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          
          span {
            color: white;
            font-size: 20px;
            font-weight: bold;
          }
        }
      }
      
      .activity-info {
        padding: 15px;
        
        .activity-title {
          margin: 0 0 10px;
          font-size: 18px;
          font-weight: bold;
          color: #303133;
        }
        
        .activity-desc {
          margin: 0 0 15px;
          color: #606266;
          height: 60px;
          overflow: hidden;
        }
        
        .activity-meta {
          margin-bottom: 15px;
          
          .meta-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            color: #606266;
            
            .el-icon {
              margin-right: 5px;
              font-size: 16px;
            }
          }
        }
        
        .activity-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .creator {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
    
    .empty-state {
      padding: 50px 0;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

@media (max-width: 768px) {
  .club-list-container {
    .page-header {
      .header-content {
        flex-direction: column;
        align-items: flex-start;
        
        h1 {
          margin-bottom: 15px;
        }
        
        .actions {
          width: 100%;
          flex-direction: column;
          
          .search-input {
            width: 100%;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
}
</style> 